#!/usr/bin/env python2.7

# bender.py

import os, sys
#import re
#from datetime import datetime, timedelta
#from dateutil.parser import parse
import numpy as np
from scipy.ndimage import gaussian_filter1d

import matplotlib
matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4']='PySide'
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

from metlib.kits import isinteger
#from mpl_toolkits.basemap import Basemap
#from matplotlib import mlab
#from netCDF4 import Dataset
from PySide.QtCore import *
from PySide.QtGui import *
from ui_grad import *

def nograd(data, *args, **kwargs):
    return data.copy()

def gf1d(data, sigma, axis=-1):
    return gaussian_filter1d(data, sigma=sigma, axis=axis, mode='nearest', order=1)

def gf2d(data, sigma, axis=-1):
    return gaussian_filter1d(data, sigma=sigma, axis=axis, mode='nearest', order=2)

gradtypes = ['nograd', 'gf1d', 'gf2d']
gradtyped = dict(zip(gradtypes, [nograd, gf1d, gf2d]))

class Grad(QWidget, Ui_GradWidget):
    def __init__(self, parent=None):
        super(Grad, self).__init__(parent)
        self.setupUi(self)
        self.parent = parent
        self.sigmaLabel.setNum(self.sigmaSlider.value())
        self.gradtypeBox.addItems(gradtypes)
        self.gradtype = 'gf1d'
    
    def grad(self, data, bin_size, axis=-1, fill=True):
        data = data.copy()
        if fill:
            cbi = np.argmax(~(data > 0.0), axis=axis)
            level0_bad = ~(data[:, 0] > 0.0)
            for i in range(len(cbi)):
                if cbi[i] > 0:
                    data[i, cbi[i]:] = data[i, cbi[i]-1]
                elif cbi[i] == 0 and level0_bad[i]:
                    data[i, :] = np.nan
        return self.gradfunc(data, self.sigma/bin_size, axis)

    @property
    def gradtype(self):
        return self.gradtypeBox.currentText()

    @gradtype.setter
    def gradtype(self, value):
        self.gradtypeBox.setCurrentIndex(self.gradtypeBox.findText(value))

    @property
    def gradfunc(self):
        return gradtyped.get(self.gradtype, nograd)

    @property
    def sigma(self):
        return float(self.sigmaSlider.value())
    
    @sigma.setter
    def sigma(self, value):
        self.sigmaSlider.setValue(value)


if __name__ == '__main__':
    pass
